using System;
using System.Collections.Generic;
using System.Reflection;
using MoonFramework.Attribute;
using MoonFramework.Scripts.View.UI;
using Sirenix.OdinInspector;
using UnityEngine;

namespace MoonFramework.Template
{
    [CreateAssetMenu(fileName = "GameConfigSeeting", menuName = "MoonFramework/GameConfigSetting")]
    public class GameConfigSetting : BaseConfig
    {
        [LabelText("对象池设置")] [DictionaryDrawerSettings(KeyLabel = "类型", ValueLabel = "皆可缓存")]
        public Dictionary<Type, bool> cacheDic = new();

        [LabelText("UI窗口设置")] [DictionaryDrawerSettings(KeyLabel = "类型", ValueLabel = "UI窗口设置")]
        public Dictionary<Type, UIElement> UIElements = new();

#if UNITY_EDITOR
        [Button("初始化游戏配置", ButtonHeight = 50)]
        [GUIColor(0, 1, 0)]
        /// <summary>
        /// 编译前执行函数
        /// </summary>
        public void InitForEditor()
        {
            PoolAttributeOnEditor();
            UIElementAttributeOnEditor();
        }

        /// <summary>
        ///     将带有Pool特性的类型加入缓存池字典
        /// </summary>
        private void PoolAttributeOnEditor()
        {
            cacheDic.Clear();
            // 获取所有程序集
            var asms = AppDomain.CurrentDomain.GetAssemblies();
            // 遍历程序集
            foreach (var assembly in asms)
            {
                // 遍历程序集下的每一个类型
                var types = assembly.GetTypes();
                foreach (var type in types)
                {
                    // 获取pool特性
                    var pool = type.GetCustomAttribute<PoolAttribute>();
                    if (pool != null) cacheDic.Add(type, true);
                }
            }
        }

        private void UIElementAttributeOnEditor()
        {
            UIElements.Clear();
            //获取所有的程序集
            var asms = AppDomain.CurrentDomain.GetAssemblies();

            var baseType = typeof(BaseUIWindow);
            //遍历程序集
            foreach (var assembly in asms)
            {
                //遍历程序集下的每一个类型
                var types = assembly.GetTypes();
                foreach (var type in types)
                    if (baseType.IsAssignableFrom(type)
                        && !type.IsAbstract)
                    {
                        var attribute = type.GetCustomAttribute<UIElementAttribute>();
                        if (attribute != null)
                            UIElements.Add(type, new UIElement
                            {
                                isCache = attribute.isCache,
                                prefab = Resources.Load<GameObject>(attribute.resPath),
                                layerNum = attribute.layerNum
                            });
                    }
            }
        }
#endif
    }
}